//
//  LoginViewController.m
//  Haliaeetus
//
//  Created by junli hou on 2018/3/24.
//  Copyright © 2018年 BMY. All rights reserved.
//

#import "LoginViewController.h"
#import "SVProgressHUD.h"
#import "SIgnUpViewController.h"
#import "ForgetPwdViewController.h"


@interface LoginViewController ()
@property (nonatomic, strong) UIButton *smsCodeBtn;
@property (nonatomic,strong) UITextField *phoneTextField;
@property (nonatomic,strong) UITextField *pswTextField;
@property (nonatomic, strong) UIButton *loginBtn;
@property (nonatomic, strong) UIButton *sigUpBtn;
@property (nonatomic, strong) UIButton *forgetPwdBtn;
@end

@implementation LoginViewController


- (instancetype)initWithLoginSuccessBlock:(LoginSuccessBlock)successBlock:(LoginCancelBlock)cancelBlock
{
    self = [super init];
    if (self) {
        _successBlock = successBlock;
        _cancelBlock=cancelBlock;
    }
    return self;
}
- (void)loadView {
    [super loadView];
    self.title =@"登录";
    self.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController setLeftBtnWithTarget:self action:@selector(goBack)];
    
    [self initView];

}
- (void)goBack {
    _cancelBlock();
    [self dismissViewControllerAnimated:YES completion:nil];

}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
      self.edgesForExtendedLayout = UIRectEdgeNone;
    
}
- (void)initView{
    
    UIImageView *helloLineView = [[UIImageView alloc]init];
    helloLineView.backgroundColor = WS_RGB(225, 134, 35);
    helloLineView.frame = CGRectMake(15,34,3,22);
    [self.view addSubview:helloLineView];
    
    
    UILabel *helloLabel = [[UILabel alloc]initWithFrame:CGRectMake(24,30,150,30)];
    helloLabel.text = @"北美游欢迎您";
    helloLabel.textColor = WS_RGBA(68,69,60,1);
    helloLabel.font = [UIFont systemFontOfSize:22];
    [self.view addSubview:helloLabel];
    
    
    //手机号码

    
    UILabel *phoneLab = [[UILabel alloc]initWithFrame:CGRectMake(15,59,85,59)];
    phoneLab.text = @"手机号码";
    phoneLab.textColor = WS_RGBA(204,204,204,1);
    phoneLab.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:phoneLab];
    
    self.phoneTextField = [[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMaxX(phoneLab.frame) + 10,59,self.view.frame.size.width - 125,59)];
    self.phoneTextField.keyboardType= UIKeyboardTypeNumberPad;
    self.phoneTextField.backgroundColor = [UIColor whiteColor];
    self.phoneTextField.font = [UIFont systemFontOfSize:16];
    self.phoneTextField.placeholder=@"请填写您的手机号码";
    [self.view addSubview:self.phoneTextField];
    
    UIImageView *lineView = [[UIImageView alloc]initWithFrame:CGRectMake(0,CGRectGetMaxY(phoneLab.frame),self.view.frame.size.width,1)];
    lineView.backgroundColor = WS_RGBA(225, 225, 225, 0.5);
    [self.view addSubview:lineView];
    
    UILabel *codeLab = [[UILabel alloc]initWithFrame:CGRectMake(15,CGRectGetMaxY(lineView.frame),65,59)];
    codeLab.text = @"密码";
    codeLab.textColor = WS_RGBA(204,204,204,1);
    codeLab.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:codeLab];
    
    //密码
    self.pswTextField = [[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMaxX(phoneLab.frame) + 10,CGRectGetMaxY(lineView.frame),self.view.frame.size.width - 125,59)];
    self.pswTextField.keyboardType= UIKeyboardTypeDefault;
    self.pswTextField.backgroundColor = [UIColor whiteColor];
    self.pswTextField.secureTextEntry=YES;
    self.pswTextField.font = [UIFont systemFontOfSize:16];
    self.pswTextField.placeholder=@"请填写您的密码";
    [self.view addSubview:self.pswTextField];
    
    UIImageView *lineView1 = [[UIImageView alloc]initWithFrame:CGRectMake(0,CGRectGetMaxY(codeLab.frame),self.view.frame.size.width,1)];
    lineView1.backgroundColor = WS_RGBA(225, 225, 225, 0.5);
    [self.view addSubview:lineView1];
    
    //登录
    self.loginBtn = [[UIButton alloc]init];
    self.loginBtn.frame =CGRectMake(15,CGRectGetMaxY(lineView1.frame) + 20,WS_SCREEN_FRAME_WIDTH-30,40);
    self.loginBtn.layer.cornerRadius=2;
    self.loginBtn.layer.masksToBounds = YES;
    self.loginBtn.backgroundColor = WS_RGB(255, 134, 35);
    self.loginBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [self.loginBtn setTitleColor:WS_RGB(255, 255, 255) forState:UIControlStateNormal];
    [self.loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [self.loginBtn addTarget:self action:@selector(VerificationPhone) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.loginBtn];
    
    
    //忘记密码
    self.forgetPwdBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.forgetPwdBtn.frame =CGRectMake(WS_SCREEN_FRAME_WIDTH-70,CGRectGetMaxY(self.loginBtn.frame) + 30,60,20);
    self.forgetPwdBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [self.forgetPwdBtn setTitleColor:WS_RGB(68, 69, 60) forState:UIControlStateNormal];
    [self.forgetPwdBtn setTitle:@"忘记密码" forState:UIControlStateNormal];
    [self.forgetPwdBtn addTarget:self action:@selector(forgetPwdAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.forgetPwdBtn];
    
    

    
    self.sigUpBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.sigUpBtn.frame = CGRectMake(15,WS_SCREEN_FRAME_HEIGHT-140,self.view.frame.size.width-40,40);
    //    _LoginBtn.frame = CGRectMake(20,self.view.frame.size.height - 90 - 40,self.view.frame.size.width-40,40);
    self.sigUpBtn.userInteractionEnabled = YES;
    [self.sigUpBtn setTitle:@"手机快速注册" forState:UIControlStateNormal];
    self.sigUpBtn.titleLabel.font = [UIFont systemFontOfSize: 16.0];
    [self.sigUpBtn setTitleColor:WS_RGBA(68, 69, 60, 1) forState:UIControlStateNormal];
    self.sigUpBtn.layer.masksToBounds = YES;
    self.sigUpBtn.layer.cornerRadius = 3;
    self.sigUpBtn.layer.borderWidth = 1;
    self.sigUpBtn.layer.borderColor = [WS_RGBA(155, 155, 155, 1)  CGColor];
    [self.sigUpBtn addTarget:self action:@selector(goSignUp) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.sigUpBtn];
    
}
-(void)forgetPwdAction{
    ForgetPwdViewController *forgetPwdViewController=[[ForgetPwdViewController alloc]init];
    
    [self.navigationController pushViewController:forgetPwdViewController animated:YES];
    
}
- (void)goSignUp{
    SIgnUpViewController *signUpViewController=[[SIgnUpViewController alloc]init];
    
    [self.navigationController pushViewController:signUpViewController animated:YES];
    
}

-(void)startTime {
    __block int timeout=60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);//GCD定时器
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [self.smsCodeBtn setTitle:@"重发验证码" forState:UIControlStateNormal];
                self.smsCodeBtn.userInteractionEnabled = YES;
                //                [identifierBtn.layer setBorderColor:[ RGBA(208, 67, 69, 1) CGColor]];//边框颜色
                [self.smsCodeBtn setTitleColor:WS_RGBA(107, 165, 248, 1) forState:UIControlStateNormal];
            });
        }else{
            NSString *strTime = [NSString stringWithFormat:@"%.2d", timeout];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                NSLog(@"____%@",strTime);
                [self.smsCodeBtn setTitle:[NSString stringWithFormat:@"%@s重新获取",strTime] forState:UIControlStateNormal];
                self.smsCodeBtn.userInteractionEnabled = NO;
                //                [identifierBtn.layer setBorderColor:[[UIColor grayColor] CGColor]];//边框颜色
                [self.smsCodeBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                
            });
            timeout--;
            
        }
    });
    dispatch_resume(_timer);
}

- (void)VerificationPhone{
    
    
    if ([self.phoneTextField.text isEqualToString:@""] || self.phoneTextField.text.length == 0) {
        WSToast(@"请输入您的手机号码")

    }else if([self.pswTextField.text isEqualToString:@""] || self.pswTextField.text.length == 0){
      WSToast(@"请输入您的密码")
   
    }else{
        
        [self doLogin];
    }
}

- (void)validateVcodeHttpRequest{
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    [params setValue:self.phoneTextField.text forKey:@"mobile"];
    [WSNetwork WSHttpsByType:@"POST" Url:[NSString stringWithFormat:@"%@%@",BMY_URL,@"/sms/sign_in"] params:params onCompletion:^(NSMutableDictionary *dic){
        if ([[dic objectForKey:@"biz_action"] intValue]==0) {
            //获取成功
            WSToast(@"验证码发送成功");
            [self startTime];
        }else{
            //错误提示
              WSToast(@"验证码发送失败，稍候重试")
        }
        
    }onError:^(NSError *error){
            WSToast(@"验证码发送失败，稍候重试")
    }];
    
}



//- (void)doSMSLogin{
//
//    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
//
//    [params setValue:self.phoneTextField.text forKey:@"mobile"];
//    [params setValue:self.codeTextField.text forKey:@"auth_code"];
//    [WSNetwork WSHttpsByType:@"POST" Url:[NSString stringWithFormat:@"%@%@",@"http://120.26.203.235:3000/api/sessions/sms_login",@""] params:params onCompletion:^(NSMutableDictionary *dic){
//        if ([[dic objectForKey:@"biz_action"] intValue]==0) {
//            //获取成功
//            WSToast(@"登录成功");
//            self.successBlock();
//            [LoginManager setUserData:[dic objectForKey:@"data"] ];
//              [self dismissViewControllerAnimated:YES completion:nil];
//        }else{
//            //错误提示
//            WSToast([dic objectForKey:@"biz_msg"]);
//        }
//
//    }onError:^(NSError *error){
//        WSToast(@"登录失败")
//    }];
//
//}

- (void)doLogin{
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    [params setValue:self.phoneTextField.text forKey:@"account"];
    [params setValue:self.pswTextField.text forKey:@"password"];
    [WSNetwork WSHttpsByType:@"POST" Url:[NSString stringWithFormat:@"%@%@",BMY_URL,@"/sessions"] params:params onCompletion:^(NSMutableDictionary *dic){
        if ([[dic objectForKey:@"biz_action"] intValue]==0) {
            //获取成功
            WSToast(@"登录成功");
            self.successBlock();
            [LoginManager setUserData:[dic objectForKey:@"data"] ];
            [self dismissViewControllerAnimated:YES completion:nil];
        }else{
            //错误提示
            WSToast([dic objectForKey:@"biz_msg"]);
        }
        
    }onError:^(NSError *error){
        WSToast(@"登录失败")
    }];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
